/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Object;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author PhongLK60473
 */
public class Order extends Book implements Serializable{
    private int Quantity=0;

    public int getQuantity() {
        return Quantity;
    }

    public void setQuantity(int Quantity) {
        this.Quantity = Quantity;
    }

    public Order(int BookId) {
        super(BookId);
        
    }
    public float getTotalPrice(){
        return this.Quantity*this.Price;
    }
    public static int isOrder(int bookid,HttpServletRequest request){
        HttpSession sess = request.getSession();
        ArrayList orders = (ArrayList) sess.getAttribute("Orders");
        Order order = Order.getOrder(bookid, request);
        if(order==null){
            return 0;
        }else{
            return order.getQuantity();
        }
    }
    public static Order getOrder(int bookid,HttpServletRequest request){
        HttpSession sess = request.getSession();
        ArrayList orders = (ArrayList) sess.getAttribute("Orders");
        if(orders==null||orders.size()==0){
            System.out.println("Orders does not init or empty");
            return null;
        } else {
            System.out.println("Ya! have money!");
            try {
                Object[] aO = orders.toArray();
                for (int i = 0; i < aO.length; i++) {
                    Order order = (Order) aO[i];
                    System.out.println("Ordered : " + order.getBookTitle());
                    if (order.getBookId() == bookid) {
                        return order;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
    public static boolean Checkout(HttpServletRequest request){
        HttpSession sess = request.getSession();
        User user = (User) sess.getAttribute("User");
        ArrayList orders=null;
        boolean rs = true;
        if (user != null && user.isCustomer()) {
            orders = (ArrayList) sess.getAttribute("Orders");
            if (orders == null) {
                rs = false;
            } else {
                
                Database db = new Database();
                    if(db.isOK){
                    Object[] ords = orders.toArray();
                    String sql;
                    PreparedStatement stm=null;
                    ResultSet rset=null;
                    int rowNum;
                    try {
                        sql = "INSERT INTO Orders (userid,statusid,date,time,Description)"
                                + " VALUES(?, ?, ?, ?, ?)";
                        stm = db.con.prepareStatement(sql,java.sql.Statement.RETURN_GENERATED_KEYS);
                        stm.setInt(1, user.getId());
                        stm.setInt(2, 1);// default status : WAITTING
                        stm.setDate(3, new java.sql.Date(new Date().getTime()));
                        stm.setTime(4, new Time(new Date().getTime()));
                        stm.setString(5, "Order of "+user.getUsername());

                        rowNum=stm.executeUpdate();

                        if (rowNum > 0) {
                            rset = stm.getGeneratedKeys();
                            rset.next();
                            int orderid = rset.getInt(1);
                            float total=0;
                            for (int i = 0; i < ords.length; i++) {
                                Order order = (Order) ords[i];
                                sql = "INSERT INTO OrderDetails"
                                        + " (orderid,bookid,quantity,totalprice)"
                                        + " VALUES(?, ?, ?, ?)";
                                stm = db.con.prepareStatement(sql);
                                stm.setInt(1,orderid);
                                stm.setInt(2, order.getBookId());
                                stm.setInt(3, order.getQuantity());
                                stm.setFloat(4, order.getTotalPrice());
                                
                                rowNum = stm.executeUpdate();
                                if(rowNum>0){
                                    //ok
                                }else{
                                    rs=false;
                                    break;
                                    //
                                }
                                total+=order.getTotalPrice();
                            }

                            sql="UPDATE Orders SET totalprice = ? "
                                    + "WHERE id = ?";
                            stm = db.con.prepareStatement(sql);
                            stm.setFloat(1, total);
                            stm.setInt(2, orderid);

                            stm.executeUpdate();
                        } else {
                            rs = false;
                        }
                        
                    } catch (Exception e){
                        e.printStackTrace();
                    } finally {
                        try {
                            rset.close();
                            stm.close();
                            db.con.close();
                        } catch (SQLException e2){
                            e2.printStackTrace();
                        }
                    }
                } else {
                        System.out.println("Cannot connect to database");
                        rs=false;
                }
            }
            
        } else {
            rs =  false;
        }
        if(rs==true){
            orders.clear();
        } else {

        }
        sess.setAttribute("Orders", orders);
        return rs;
    }

    public static boolean Order(HttpServletRequest request){
        HttpSession sess = request.getSession();
        User user = (User) sess.getAttribute("User");
        System.out.println("Order has called");
        ArrayList orders=null;
        boolean rs = true;
        if (user != null && user.isCustomer()) {
            orders = (ArrayList) sess.getAttribute("Orders");
            if (orders == null) {
                orders = new ArrayList();
            }
            int bookid = -1;
            try {
                bookid = Integer.parseInt(request.getParameter("bookid"));
            } catch (Exception e) {
                e.printStackTrace();
                bookid = -1;
            }
            if (bookid != -1) {
                Order order = new Order(bookid);
                order.setQuantity(1);
                Order oldOrder = Order.getOrder(bookid, request);
                if(oldOrder!=null){
                    oldOrder.setQuantity(oldOrder.getQuantity()+1);
                } else {
                    orders.add(order);
                }
            } else {
                rs = false;
            }
        } else {
            rs =  false;
        }

        sess.setAttribute("Orders", orders);
        return rs;
    }
}
